package cn.gzmli.dtt.common.workflow.service;

import cn.gzmli.dtt.common.config.cache.Config;
import cn.gzmli.dtt.common.entity.PageInfo;
import cn.gzmli.dtt.common.utils.BaseUtil;
import cn.gzmli.dtt.common.workflow.controller.constant.WorkFlowEnum;
import cn.gzmli.dtt.common.workflow.dao.TaskLogDao;
import cn.gzmli.dtt.common.workflow.entity.FlowNode;
import cn.gzmli.dtt.common.workflow.entity.TaskLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class TaskLogService {

	@Autowired
	private TaskLogDao taskLogDao;

	/**
	 * 条件分页查询任务记录
	 * @param condition
	 * @param pageInfo
	 * @return
	 * @throws Exception
	 */
	public List<TaskLog> queryTaskLogs(Map<String,String> condition, PageInfo pageInfo)throws Exception {

		return taskLogDao.queryEntityByPage(condition, pageInfo);

	}

	public List<TaskLog> queryTaskLogs(Map<String,String> condition)throws Exception {

		return taskLogDao.queryEntity(condition);

	}

	/**
	 * 按条件查询单个任务记录
	 * @param condition
	 * @return
	 * @throws Exception
	 */
	public TaskLog queryTaskLog(Map<String,String> condition)throws Exception {

		return taskLogDao.queryOnlyEntity(condition);

	}

	public TaskLog queryTaskLog(Integer id)throws Exception {
		return taskLogDao.get(id);
	}

	/**
	 * 更新节点任务记录为回滚状态
	 * @param bID
	 * @param tID
	 * @param nextNodes
	 * @return
	 * @throws Exception
	 */
	public Map<String,Object> updateTaskLogForRecall(Integer bID, Integer tID, FlowNode curFlowNode, List<Map<String,Object>> nextNodes)throws Exception {

		Map<String,Object> result=new HashMap<String,Object>();

		if(nextNodes!=null){

			Map<String,Object> workFlow  = Config.getWorkFlowConf(curFlowNode.getWorkFlowId());

			//获取节点信息
			Map<String,Object> nodeInfo=(Map<String,Object>)workFlow.get(curFlowNode.getId());
			//获取业务实体定义信息
			Map<String,Object> bEntityInfo=(Map<String,Object>)nodeInfo.get("bEntityInfo");

			Integer bStatus=nodeInfo.get("bStatus")==null?null:
					Integer.parseInt(nodeInfo.get("bStatus").toString());

			Integer tStatus=nodeInfo.get("tStatus")==null?null:
					Integer.parseInt(nodeInfo.get("tStatus").toString());

			String bEntityName=bEntityInfo.get("bEntityName")==null?null:bEntityInfo.get("bEntityName").toString();

			String bStatusKey=bEntityInfo.get("bStatusKey")==null?null:bEntityInfo.get("bStatusKey").toString();

			String idKey=bEntityInfo.get("idKey")==null?null:bEntityInfo.get("idKey").toString();

			boolean isRecall = false;
			List<String> recallSqls=new ArrayList<String>();

			if(!BaseUtil.isNotEmpty(bStatus)){
				result.put("status",0);
				result.put("msg","回滚失败！未定义节点默认业务状态。");
				return result;
			}else if(!BaseUtil.isNotEmpty(tStatus)){
				result.put("status",0);
				result.put("msg","回滚失败！未定义节点默认任务状态。");
				return result;
			}else if(!BaseUtil.isNotEmpty(idKey)){
				result.put("status",0);
				result.put("msg","回滚失败！未定义实体信息bEntityInfo,idKey。");
				return result;
			}else if(!BaseUtil.isNotEmpty(bEntityName)){
				result.put("status",0);
				result.put("msg","回滚失败！未定义实体信息,bEntityName。");
				return result;
			}else if(!BaseUtil.isNotEmpty(bStatusKey)){
				result.put("status",0);
				result.put("msg","回滚失败!未定义实体信息bEntityInfo,bStatusKey。");
				return result;
			}



			String selBEntitySql= String.format("SELECT * FROM %s WHERE %s=%s",bEntityName,idKey,bID);

			Map<String,Object> bEntity=taskLogDao.getJdbcTemplate().queryForMap(selBEntitySql);

			Integer curBStatus= Integer.parseInt(bEntity.get(bStatusKey).toString());

			for(Map<String,Object> nextNode:nextNodes){

				String nextNodeID=nextNode.get("id")==null?"":nextNode.get("id").toString();
				String nextNodeName=nextNode.get("name")==null?"":nextNode.get("name").toString();
				int nodeType= Integer.valueOf(nextNode.get("nodeType").toString());

				//获取节点信息
				Map<String,Object> nextNodeInfo=(Map<String,Object>)workFlow.get(nextNodeID);

				if(nextNodeInfo==null){
					continue;
				}

				Integer nextBStatus=nextNodeInfo.get("bStatus")==null?null:
						Integer.parseInt(nextNodeInfo.get("bStatus").toString());



				if(nodeType== WorkFlowEnum.FlowNodeType.开始.getValue()){
					continue;
				}else if(nodeType== WorkFlowEnum.FlowNodeType.分支.getValue()){
					continue;
				}else if(nodeType==WorkFlowEnum.FlowNodeType.合并.getValue()){
					continue;
				}else if(nodeType==WorkFlowEnum.FlowNodeType.流程线.getValue()){
					continue;
				}else if(nodeType==WorkFlowEnum.FlowNodeType.结束.getValue()){
					continue;
				}




				if(!BaseUtil.isNotEmpty(nextBStatus)){
			/*result.put("status",0);
			result.put("msg","回滚失败！回滚的节点:"+nextNodeName+"未定义节点默认业务状态。");*/
					continue;
					//return result;
				}




				String setCurVersion= String.format("SELECT "
						+ "@curVersion:=IF(MAX(version) IS NULL,1,MAX(version)) FROM Tasklog "
						+ "WHERE flowNodeID='%s' AND formID=%s",nextNodeID,bID);
				String updateNextSql= String.format("UPDATE TaskLog SET status=999 "
						+ " WHERE formID=%s AND flowNodeID ='%s' "
						+ "AND version=@curVersion",bID,nextNodeID);

				//如果下一个节点有状态和当前业务状态匹配，则可以执行撤回
				if(curBStatus.equals(nextBStatus))
				{
					isRecall=true;
				}

				recallSqls.add(setCurVersion);

				recallSqls.add(updateNextSql);




			}

			String updateTStatusSql= String.format("UPDATE TaskLog SET status=%s "
					+ " WHERE id=%s ",tStatus,tID);

			String updateBStatusSql= String.format("UPDATE %s SET %s=%s "
					+ " WHERE %s=%s ",bEntityName,bStatusKey,bStatus,idKey,bID);

			recallSqls.add(updateTStatusSql);
			recallSqls.add(updateBStatusSql);

			//如果当前业务状态允许撤回，执行撤回状态更新操作
			if(isRecall){
				for(String sql:recallSqls){
					taskLogDao.getJdbcTemplate().execute(sql);
				}
			}else{
				recallSqls.clear();
				result.put("status",0);
				result.put("msg","撤回失败，业务状态已改变，当前节点无法执行撤回操作！");
				return result;
			}

		}

		result.put("status",1);
		result.put("msg","撤回成功！");
		return result;

	}


}
